'use strict';

const { Service } = require('egg');
const ModelName = 'StaffBalance'
class RouterService extends Service {
  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [
        {
            model: this.ctx.model.Staff,
        }
      ]
    });
  }

  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
    });
  }
  async findOne(id) {
    return this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
    });
  }
  async add(data) {
    // staff余额增加 金额
    console.log('data',data)
    await this.ctx.model.Staff.update({
      balance: this.app.Sequelize.literal(`balance + ${data.amount}`)
    }, {
      where: {
        id: data.staff_id
      }
    })
    return this.ctx.model[ModelName].create(data);
  }
  async create(data) {
    return this.ctx.model[ModelName].create(data);
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }
  async audit(id, data) {
    try {
      if (data.status === 1) {
        const find = await this.findOne(id)
        const amount = parseFloat(find.dataValues.amount)
        const findStaff = await this.ctx.model.Staff.findOne({
          where: {
            id: find.dataValues.staff_id
          }
        })
        const staff = findStaff.dataValues
        const balance =  parseFloat(staff.balance)
        if (balance < amount) {
          throw new Error('余额不足')
        }
        // 通过 扣钱
        await this.ctx.model.Staff.update({
          balance: this.app.Sequelize.literal(`balance - ${amount}`)
        }, {
          where: {
            id: find.dataValues.staff_id
          }
        })
      }
    } catch (e) {
      console.log(e)
      throw new Error(e)
    }
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }
  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }
}

module.exports = RouterService;
